# -*- coding: utf-8 -*- 
try:
    import cPickle as pickle
except:
    import pickle
import uuid    
import tornado.web   
from pymongo.objectid import ObjectId as _id
import time
import datetime
one_day = datetime.timedelta(days=1)
one_hour = datetime.timedelta(hours=1)

def time_fmt(value):     
    tm_now = time.localtime()    
    
    tm_lastday = (datetime.date.today() - one_day).timetuple() 
    tm_today = datetime.date.today().timetuple()
    tm_lasthour = (datetime.datetime.now() - one_hour).timetuple()
    
    t = tm_value = time.localtime(value) 
    if tm_value.tm_year < tm_now.tm_year: 
        return u'%d年%d月%d日 %02d:%02d'%(t.tm_year,t.tm_mon,t.tm_mday,t.tm_hour,t.tm_min)
    
    if tm_value > tm_lasthour:
        minutes = (tm_now.tm_min-t.tm_min+60)%60
        if minutes > 0:
            return u'%d分钟前'%minutes
        else: 
            return u'刚刚'
    
    if tm_value > tm_today:
        return u'今天 %02d:%02d'%(t.tm_hour,t.tm_min)
    
    if tm_value > tm_lastday:
        return u'昨天 %02d:%02d'%(t.tm_hour,t.tm_min)
    
    return u'%d月%d日 %02d:%02d'%(t.tm_mon,t.tm_mday,t.tm_hour,t.tm_min)
 

cache_users = { }
class BaseHandler(tornado.web.RequestHandler):     
    @property  
    def db(self):  #get application mongodb instance
        return self.application.db 
     
    @property
    def static_url(self):
        return self.settings['static_url']
    
    @property
    def upload_path(self):
        return self.settings['upload_path']
    
    @property
    def download_url(self):
        return self.settings['download_url']
    
    
    def get_current_user(self): #get current logged in user
        if self.get_cookie('email', None) is None: 
            return None
        user = {
            'uid': self.get_cookie('uid', None),
            'email': self.get_cookie('email', None) ,
            'name': self.get_cookie('name', None) 
        }
        return user
    
    @property  
    def cached_users(self): 
        return self.application.cached_users
    
    def cache_user(self,user): #to cache use 
        uid = str(user['_id'])
        self.cached_users[uid] = user
    
    def user(self,uid): #load user from cache
        uid = str(uid)
        if uid in self.cached_users: return self.cached_users[uid]
        u = self.db.users.find_one({'_id':_id(uid)})
        if u is None: return None
        self.cache_user(u)
        return u
    
    def load_user(self,email): #load user via email
        u = self.db.users.find_one({'email': email})
        if u is not None:   
            self.cache_user(u)
        return u
 
        
class LoginHandler(BaseHandler): 
    def get(self):  
        self.render('login.html')
         
    def post(self): 
        email = self.get_argument('email')
        password = self.get_argument('password')
        res = {'status': '0'}
        user = self.load_user(email)
        if user is None:
            res['status'] = '-1'
        elif user['password'] == password:  
            self.set_cookie('email',email) 
            self.set_cookie('name',user['name']) 
            self.set_cookie('uid',str(user['_id']))    
            res['user'] = user['name']
            res['profile_url'] = '%s/img/0.jpg'%self.settings['static_url']
        else:
            res['status'] = '-2' 
        self.write(res)

class LogoutHandler(BaseHandler):  
    def get(self):
        self.clear_cookie('uid')  
        self.clear_cookie('email')
        self.clear_cookie('name') 
        self.redirect('/')


class SettingsHandler(BaseHandler):  
    def get(self):    
        self.render('settings.html')
  
   
class FileHandler(BaseHandler):  
    def get(self):
        self.write('ok')
        
    def post(self):    
        qqfile = self.get_argument('qqfile') 
        suffixIndex = qqfile.rfind('.')
        suffix = ''
        if suffixIndex != -1:
            suffix = qqfile[suffixIndex:]
        filename = '%s%s'%(uuid.uuid4(),suffix)    
        storefilepath = '%s/%s'%(self.upload_path, filename)
            
        storefile = open(storefilepath,'w')
        storefile.write(self.request.body) 
        storefile.close() 
        res = {'success': 'true','url':'%s/%s'%(self.download_url,filename)} 
        self.write(res)
        
class RegisterHandler(BaseHandler):
    def get(self):   
        self.render('register.html')  
        
    def post(self):    
        email = self.get_argument('email')
        name = self.get_argument('name')
        password = self.get_argument('password')
        res = {'status': '0'}
        if self.db.users.find_one({'email': email}):
            res['status'] = '-1' #email exists
        if self.db.users.find_one({'name': name}):
            res['status'] = '-2' #nickname exists
        
        if res['status'] != '0':
            self.write(res)
            return
        
        user = {
            'email': email,
            'name': name,
            'password': password,
        }
        self.db.users.save(user) 
        self.write(res)

class BackupLoginHandler(BaseHandler):  
    def get(self):  
        self.render('login.html')
    
    def post(self):
        email = self.get_argument('email')
        password = self.get_argument('password') 
        if username==password:
            self.set_cookie('email',email)
            next_url = self.get_argument('next','/') 
            self.redirect(next_url)
        else:
            self.redirect('/auth/login')        
 
   
class HomeHandler(BaseHandler):  
    def latest_threads(self,count=10):
        cursor = self.db.threads.find({},{'title':1,'created_at':1,'uid':1}).sort('created_at',-1).limit(count)
        threads = []
        for thread in cursor:
            threads.append(thread)
        for thread in threads:
            thread['user'] = self.user(thread['uid'])
        return threads
    
    def get(self):  
        forum_threads = self.latest_threads()
        self.render('home.html',threads=forum_threads)

class TestHandler(BaseHandler):   
    def get(self):   
        self.render('test/test.html')

class CheckEmailHandler(BaseHandler):   
    def post(self):
        email = self.get_argument("email",None)
        user = self.db.users.find_one({'email': email},{'_id':1})  
        res = {'status': '0'}
        if user is None: res['status'] = '-1'
        self.write(res)

handlers = [
    ('/', HomeHandler),
    ('/test', TestHandler),
    ('/settings', SettingsHandler),
    ('/check/email', CheckEmailHandler),
    ('/upload', FileHandler),
    ('/register', RegisterHandler),
    ('/auth/login', LoginHandler), 
    ('/auth/logout', LogoutHandler)
] 